package cc.vv;

import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDex;

import java.util.LinkedList;
import java.util.List;

import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.lkbasecomponent.base.app.LKBaseApplication;

/**
 * Created by sun.li on 2018/6/6.
 *
 * @author sun.li
 */

public class BaseNewApplication extends LKBaseApplication {

    public List<Activity> mActivityList;

//    private static BaseNewApplication mInstance;
//
//    public static BaseNewApplication getInstance() {
//        if (null == mInstance) {
//            synchronized (BaseNewApplication.class) {
//                if (null == mInstance) {
//                    mInstance = new BaseNewApplication();
//                }
//            }
//        }
//        return mInstance;
//    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (null == mActivityList) {
            mActivityList = new LinkedList<>();
        }
//        LeakCanary.install(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    /**
     * 添加activity到容器中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (activity != null && !mActivityList.contains(activity)) {
            mActivityList.add(activity);
        }
    }

    public void removeActivity(Activity activity) {
        if (activity != null && mActivityList.contains(activity)) {
            mActivityList.remove(activity);
        }
    }


    /**
     * 遍历所有的Activity并finish
     */
    public void exitApp() {
        try {
            for (int i = 0; i < mActivityList.size(); i++) {
                Activity activity = mActivityList.get(i);
                if (null != activity) {
                    activity.finish();
                }
            }
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
    }

    /**
     * 遍历指定的Activity并finish
     */
    public void exit(int num) {
        for (int i = 1; i <= num; i++) {
            if (mActivityList.size() >= num) {
                Activity activity = mActivityList.get(mActivityList.size() - i);
                if (activity != null) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * 从集合中移除activity并finish
     */
    public void finishActivityAndRemove() {
        Activity activity = mActivityList.get(mActivityList.size() - 1);
        mActivityList.remove(mActivityList.size() - 1);
        if (activity != null) {
            activity.finish();
        }
    }






}
